from flask import Flask, request, redirect, url_for, session, send_from_directory
import config
from exts import db
from flask_migrate import Migrate
from buleprints.employees import bp as em_bp
from buleprints.daypaper import bp as dp_bp
from buleprints.login import bp as lg_bp
from apscheduler.schedulers.background import BackgroundScheduler
from services.daypaper_service import update_daypaper, uncommitted_report
from utils import wait_db

app = Flask(__name__)  # 创建 Flask 应用实例

app.config.from_object(config)  # 从配置文件加载配置

# 连接数据库并等待直到数据库可用
db_uri = app.config['SQLALCHEMY_DATABASE_URI']  # 从配置中获取数据库 URI
if not wait_db(db_uri):
    print("无法连接到数据库，退出应用。")
    exit(1)

db.init_app(app)  # 绑定数据库实例到 Flask 应用

app.register_blueprint(em_bp)
app.register_blueprint(dp_bp)
app.register_blueprint(lg_bp)

migrate = Migrate(app, db)  # 初始化数据库迁移

# 初始化调度器
scheduler = BackgroundScheduler()


# 添加定时任务
def scheduled_update_daypaper():
    with app.app_context():  # 为更新日报包装一层应用上下文，确保在应用上下文中运行
        print("启动自动更新日报")
        update_daypaper()  # 调用更新日报函数
        uncommitted_report()  # 调用发送提醒日报


scheduler.add_job(scheduled_update_daypaper, 'cron', hour=10, minute=0)  # 设置定时任务

# 创建拦截器
@app.before_request
def interceptor():
    if request.endpoint in ['login.login']:
        return

    # 允许访问所有静态资源
    static_files = [
        '/static/paper/plugins/element-ui/index.css',
        '/static/paper/styles/common.css',
        '/static/paper/styles/login.css',
        '/static/paper/styles/icon/iconfont.css',
        '/static/paper/plugins/vue/vue.js',
        '/static/paper/images/login/logo.png',
        '/static/paper/js/request.js',
        '/static/paper/plugins/element-ui/index.js',
        '/static/paper/api/login.js',
        '/static/paper/js/validate.js',
        '/static/paper/plugins/axios/axios.min.js',
        '/static/paper/styles/icon/iconfont.woff2',
        '/static/paper/favicon.ico'
    ]

    # 允许访问静态文件
    if request.path in static_files:
        return

    if 'user_id' not in session:
        return redirect(url_for("login.login"))


# 启动调度器
scheduler.start()

@app.route('/')
def hello():
    return send_from_directory('static/paper', 'index.html')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3048, debug=True)
